
"use strict";
// store user action state 
// set, get user state 
function CSPUserMgr () {
	
	this.user_states = [

	];
	
	this.servers = {
		 'hipo': {name:'hipo', serverurl: 'http://k2.emrosswar.com/'} ,
		 'Ania':	{name:'Ania', serverurl: 'http://s103.emrosswar.com/'} ,
		 'tapsg':	{name:'tapsg', serverurl: 'http://k1.tapsg.com/'} ,
	};
	
	this.refs = [
				/*
					TAP SG :: 
				*/
			{ref: 'mp001' ,
		server: 'tapsg', 
		users : [
			 [ 'hmpc3', 'tapsg', 'mp001', 'e7456578337878989886586798787628985' , '12', 'tapsg'],
			[ 'hmpd4', 'tapsg', 'mp001', 'e7456578452325346456586798787628985' , '12', 'tapsg'],
			[ 'hmpa1', 'tapsg', 'mp001', 'e745657834453462234aab6798787628985' , '12', 'tapsg'],
			// [ 'hmpb2', 'tapsg', 'mp001', 'e7456578337878989886586798787628985' ,'12',  'tapsg'],
				] },
		
	{ref: 'james' ,
	server: 'tapsg', 
	users : [
		[ 'hjamc3', 'tapsg', 'james', 'e7456578452325342346586798787628985' , '12', 'tapsg'],
		[ 'hjamb2', 'tapsg', 'james', 'e7456578452325456856586798787628985' , '12', 'tapsg'],
		[ 'hjamd4', 'tapsg', 'james', 'e7456578452325349676586798787628985' , '12', 'tapsg'],
		[ 'hjame5', 'tapsg', 'james', 'e7456578452325456456586798787628985' , '12', 'tapsg'],
		[ 'hjamf6', 'tapsg', 'james', 'e7456578452325346456587808787628985' , '12', 'tapsg'],
		[ 'hjamg7', 'tapsg', 'james', 'e7456578452325876556786798787628985' , '12', 'tapsg'],
		[ 'hjamh8', 'tapsg', 'james', 'e7456578452323098643586798787628985' , '12', 'tapsg'],
		[ 'hjami9', 'tapsg', 'james', 'e7456578452325346456598654325628985' , '12', 'tapsg'],
		[ 'hjama1', 'tapsg', 'james', 'e7456578452325346456586798754322985' , '12', 'tapsg'],
	] },
				
	];

	
	// 2nd generation  : hhyuna1
			// 0 : name,  1: server, 2 : ref , 3: dev code 
	// default  array.. 
/*
	this.sp_users = [
		'hhyune5',
		'hhyunf6'
	];*/

	
	// this.initialize();
};


CSPUserMgr.prototype = {
	objName: 'CSPUserMgr',
	
	
	initialize: function() {
	},
	
	makeUserDB: function() {
		var self = this;
		// make user info  &  append db  :
		$.each ( this.sp_users , function(i, u) {
			
			// add name 
			CDB.users.push( u[0] );	// naem 
			// add user data
			var server_info = self.servers [ u[1] ];
			
			var passwd = '12';
			if ( u[4]) {
				passwd = u[4];
			}
					
			// set game type 
			var game_type = 'emross';
			if (  u[5] ) {
				game_type = u[5];
			}
			
			var nick = u[6];
			var quit_after_donate = u[7];
			CDB.userdata.push( 
				{
				name: u[0] ,  // CGSN.341345608567535   ref : hyungc
				'nick' : nick,
				'game': game_type, 
				'serverinfo': server_info,
				device: CDB.devices[em.device.iphone],
				device_code: u[3],		// random code 
				'password': passwd,
				castles: [],
				options : { sp30: true,  },
				'quit_after_donate' : quit_after_donate,
				ref: u[2],
				key: '',			// random  invalid .. 
			});
			

			// sp 30 action states  
			/*
							self.cstls[i].setUserCityInfo(cstlinfo);	// // {"id":3070,"name":"\ucc9c\uc0c1\uc131","landtype":3,"x":185,"y":53}, 
			self.cstls[i].updateRes(res);
			self.cstls[i].updateSols(sols);
			self.cstls[i].updateCdlist(cds);
			self.cstls[i].updateCityInfo(city);
			self.cstls[i].updateStudies(studies);
			*/
			// name , castles , step, sub : , 
			var states = {name : u[0], castles: [] ,  step: 1, sub: 1 , exist: true } ;
			self.user_states.push( states );
		});
	},
	
	userCnt: function() {
		return this.sp_users.length;
	},
	
	
	// 
	getUserStates: function(idx) {
		var user = this.sp_users[idx];
		if ( !user ) {
			debug.log(this, 'Invalid user Idx');
			return;
		}
		
		return this.getUserStatesByName(user[0]);
	}, 
	
	getUserStatesByName: function(username) {
		var found_u;
		$.each ( this.user_states , function(i, u) {
			if ( u.name == username ) {
				found_u = u;
				return false;
			}
		});
		
		return found_u; 
	}, 
	
	
	setUserStates: function(user_state) {
		var self = this;;
		$.each ( this.user_states , function(i, u) {
			if ( u.name == user_state.name ) {
				$.extend ( u , user_state);
			
				debug.log( self, ' Update Success::');
				return false;
			}
		});
	}, 
	
	getAllRefs: function(ref) {
		return this.refs;
	},
	setRefererGroup: function(ref) {
		var self = this;
		
		// replace sp_users with ref .. 
		var found_refs = this.refs.filter ( function (el) { return el.ref == ref;}) ;
		var found_ref  =  found_refs[0];
		if ( ! found_ref) { 	alert('no Matched Ref'); return; 		}
		
		this.sp_users = found_ref.users;
		
		// with sp_users
		this.makeUserDB();
		// update ui 
		$('#refname').text( ref + ':' +  found_ref.server	 );
	}, 
	
};




function CSPProxy () {
	this.cur_user_s = {};
	this.initalize();
};

CSPProxy.prototype  = {
	objName: 'CSPProxy',
	
	initalize: function() {
		
	},

	changeCurUser: function(user_states) {
		
		this.cur_user_s = user_states;
	},
	
	// start sp action s
	start_sp30 : function() {
		
		if ( ! this.cur_user_s.initQ ) {
			debug.log(this, 'Create Init Qst' , this.cur_user_s);
			this.cur_user_s.initQ = new CInitQuest();
		}
		
		// restart : later 
		// TODO :  restart ---  : stop & start or...  
		this.cur_user_s.initQ.initialize();		// get prev stored state
		
		debug.log(this, 'Start Init Qst Mode');
		
		this.cur_user_s.initQ.start();	
		
	},
	
};

$(document).ready(function() {

	// cbs 
		em.cbs= {};
		
		// for cstl move & wave 
		em.cbs.cstlmove1done = $.Callbacks( "unique stopOnFalse" );	
		em.cbs.cstlwavedone = $.Callbacks( "unique stopOnFalse" );
		
			
		// login new user : got new key 
		em.cbs.userlogin = $.Callbacks("unique stopOnFalse");
		
		// when completed select new user : start GM  -> new login : get system task api :: then fire . :  reset all prev datas  
		em.cbs.userchanged = $.Callbacks("unique stopOnFalse");
			// when start user change :  to notify free prev resource  
		em.cbs.startuserchange = $.Callbacks("unique stopOnFalse");
		
		// all hero list update
		em.cbs.heroupdate = $.Callbacks("unique stopOnFalse");
		// hnting avaliable h list update 
		em.cbs.warableHpdate = $.Callbacks("unique stopOnFalse");
		
		// hnt  : 1 da hnt 1 time end cb  for cals end time : decide next ctsl
		em.cbs.hntdone = $.Callbacks("unique stopOnFalse");
		// 1 cstl att is done !!
		em.cbs.autoCstlAttDone = $.Callbacks("unique stopOnFalse");  
		// update cstl 's sols '
		em.cbs.updatesols = $.Callbacks("unique stopOnFalse");
		
		// sols trained finished  
		em.cbs.soltraindone = $.Callbacks("unique stopOnFalse");
		
		// global contorl cb 
		em.cbs.forcestop = $.Callbacks("unique stopOnFalse");
		
		// timer for desc time info  
		em.cbs.sectimer = $.Callbacks("unique stopOnFalse");
		
		
	// global 
		// var users = CDB.users;//[ 'james', 'greate'];
		// var devices = CDB.devices;//['iphone', 'android' ] ;
		
	// em.cstlview = new CCstlView();
	// em.cstlview.initialize();

/*

	em.sp30view = new CSP30View();

	// sp30 mode . info -> sp30 view. 
	em.infoview = em.sp30view ;
	// em.infoview.initialize();
//	em.infoview.connected();	*/

		
	em.cstlmgr = new CCstlMgr();
	em.cstlmgr.cstlwave_initialize();



	em.query = new CQuery();
	em.query.initialize();

	em.util = new CUtil();
		
	em.tasks = new CTasks();
	
	em.worldDA = new CWorldDA();
	
	em.hntmgr = new CHuntMgr();
	em.hntmgr.initialize();
	
	em.controller = new CController();
	
	em.scaning = new CScaning();
	em.scaning.initialize();

	em.hdrinmgr = new CHDrinMgr();
	
	
	// start monotor !!
	em.jobmonitor.registerCBs();
	em.jobmonitor.startMonitor();

	



	em.spusermgr = new CSPUserMgr();
	
	em.spproxy = new CSPProxy();
	
	em.spactmgr = new CSpActionMgr();
	//======================= TEST code here ========================
	// set login defualt user 'Greateload' for test 
	// em.controller.login('Greateload');
		

	


	/*
		 set nav with ref names 
		 
	*/
	$.each ( em.spusermgr.getAllRefs() , function(i, r ) {
		//$('.menu li').eq(i).text( r.ref );
		$('.menu li').eq(i).find('a').text( r.ref );
	});
	

/*
	 install click handler 
*/

			
			// ref select 
		$('.menu li').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();
			
			//Get the A tag
			console.log( this, $(this), $(this).text() );
			// var id = $(this).attr('href');
			console.log( e, e.target, e.target.text)	;	

			var referer = $(this).text();
	
			// stop cmd..  .. <-no : 1 more click start.. 
			if ( referer == 'stop') {
				em.cbs.forcestop.fire();
				em.controller.finishDone();
				em.jobmonitor.force_stop = false;
				alert('pause');
				return;
			}
			// start group of ref 
			debug.log( this, ' START REF GROUP ', referer);
			em.spusermgr.setRefererGroup( referer);
			 
		});
   
   
   		// start sp job  when load completed...  
   		
   			$('.container1').click(function(e) {
				em.curOp ^= em.Operation.SP30ACTION;
				
				//$("#id_btn_buytrade").toggleClass('control_modeon');
				
				if ( em.curOp & em.Operation.SP30ACTION) {
					// debug.log(this,  ' SP30ACTION clicked ' , em.curOp.toString(16) );
					
					debug.log( this, '::info  : ');
					
					em.jobmonitor.addJob( {name: 'SP30ACTION', fn: em.jobmonitor.doSP30Action, param: undefined });
					em.jobmonitor.doMonitor();
					return;
				}	else {
					debug.log(this,  ' Mode release  ' , em.curOp.toString(16));
				}	   		
			});
});
  





